import { API } from './BaseApi'
import Utils from '../../vue2-flow/src/utils/Common'
import SystemApi from './SystemApi'
import { useFlowStore } from "@/store/modules/flow/flowStore";
import { FlowApi } from "@/api/FlowApi";


class FlowRuntimeApi {

  constructor () {
    this.FlowStore = useFlowStore()
  }

  /**
   * 获取当前正在执行的流程文件
   * @param FlowId
   * @param callbaak
   * @returns {Promise<null>}
   * @constructor
   */
  GetCurrentFlow (FlowId, callbaak) {
    if (Utils.IsEmpty(FlowId)) {
      const CurrentFlow = this.FlowStore.CurrentFlow
      FlowId = CurrentFlow?.id
    }
    if (Utils.IsEmpty(FlowId) || FlowId <= 0) {
      return null
    }
    FlowApi.Get(FlowId).then(res => {
      callbaak(JSON.parse(res.Data))
    })
  }

  /**
   * 添加流程
   * @returns {Promise<*>}
   * @constructor
   */
  async AddFlow (callback) {
    const _flow = await FlowApi.Save()
    callback(_flow.Data)
  }

  /**
   * 删除流程
   * @param callback
   * @returns {Promise<void>}
   * @constructor
   */
  async DeleteFlow (id, callback) {
    const index = await API.FlowRuntimeApi.DeleteFlow(id)
    callback(index)
  }

  /**
   * 保存所有流程
   * @constructor
   */
  SaveFlow (btn) {
    API.FlowRuntimeApi.SaveAllFlow()
  }

  OpenForm (btn) {
    new SystemApi().OpenForm()
  }

  /**
   * 获取所有流程文件
   * @returns {Promise<*>}
   * @constructor
   */
  async GetAllFlowFiles (callback) {
    const nws = await API.FlowRuntimeApi.GetAllFlowFile()
    callback(JSON.parse(nws))
  }

  /**
   * 执行流程
   * @param FlowId 执行流程ID
   * @constructor
   */
  RunFlow (FlowId = null) {
    if (Utils.IsEmpty(FlowId)) {
      const CurrentFlow = this.FlowStore.CurrentFlow
      FlowId = CurrentFlow.id
    }
    FlowApi.RunFlow(FlowId)
  }

  /**
   * 流程ID
   * @param FlowId
   * @param callback
   * @constructor
   */
  StopFlow (FlowId, callback) {
    const CurrentFlow = this.FlowStore.CurrentFlow
    if (Utils.IsEmpty(FlowId)) {
      FlowId = CurrentFlow.id
    }
    FlowApi.StopFlow(FlowId).then((res) => {
      callback(res)
    })
  }

  /**
   * 修改流程
   * @param FlowInfo
   * @param Callback
   * @constructor
   */
  UpdateFlowInfo (FlowInfo, Callback) {
    FlowApi.UpdateFlow(FlowInfo).then(res => {
      Callback(res)
      this.FlowStore.SetAllFlow()
    })
  }

  GetFlowParamStructure (Callback) {
    API.FlowRuntimeApi.GetFlowParamStructure().then(res => {
      Callback(JSON.parse(res))
    })
  }
}

export default FlowRuntimeApi
